<template>
  <view class="view-class">
    <u-navbar back-text="返回" title="报修申请"></u-navbar>
    <view class="view-box">
      <u-form :model="form" ref="uForm" label-width="180" label-align="center">
        <u-form-item required label="报修人" prop="repairsName"><u-input  v-model="form.repairsName" disabled/></u-form-item>
        <u-form-item required label="联系电话" prop="phoneNumber"><u-input v-model="form.phoneNumber" type="number" disabled/></u-form-item>
        <u-form-item required label="宿舍楼栋" prop="building"><u-input v-model="form.building" type="number" disabled/></u-form-item>
        <u-form-item required label="房间号" prop="roomId"><u-input v-model="form.roomId" type="number" disabled /></u-form-item>
        <u-form-item required label="报修项目" prop="repairsProject"><u-input v-model="form.repairsProject2" :disabled="isSuccess"  type="select"  @click="repairsProjectFunc"/></u-form-item>
        <u-form-item  label="备注" prop="remark"><u-input v-model="form.remark" :disabled="isSuccess" /></u-form-item>
        <u-form-item required label="照片上传" prop="bedImages">
          <u-upload width="160" height="160" max-count="6" :header="uploadHeader"  :action="clUplodUrl" @on-remove="uploadRemove" @on-success="uploadSuccess"
                    ref="handIdCardUpload" ></u-upload>
        </u-form-item>
        <u-form-item required label="视频上传" prop="bedImages">
          <cl-upload  v-model="videoList" cloudType="other" :headers="uploadHeader" :listStyle="{
              columns: 2,
              columnGap: '20rpx',
              rowGap:'20rpx',
              height:'166rpx',
              radius:'20rpx'
          }" :action="clUplodUrl"  @onSuccess="onSuccess" fileType="video" :sourceType="['camera ', 'album']">
            <template v-slot:addImg>
              <view class="newAddImg">
                <u-icon  name="plus" size="40"></u-icon>
                <text >选择视频</text>
              </view>
            </template>
          </cl-upload>
        </u-form-item>
      </u-form>
      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc" v-if="!isSuccess">提交</u-button>
      <u-button style="position: fixed;bottom: 0;left: 0;width: 100%;z-index: 9" type="primary" @click="submitFunc('success')" v-else>完成</u-button>
    </view>
    <u-select v-model="showContactRelationSel" :list="contactRelationList" mode="single-column"
              @confirm="selectedContactRelation"></u-select>
    <u-top-tips ref="uTips"></u-top-tips>
    <u-modal v-model="show" confirm-text="退出"
             title="提示"  @confirm="submitFunc('success')"
    >
      <view class="u-update-content">
        <rich-text style="text-align: center;padding: 30rpx" :nodes="content"></rich-text>
      </view>
    </u-modal>
  </view>
</template>
<script>
import {compressImg} from '@/utils/compressor/compress.js'
import {uploadImg} from '@/utils/upload.js'
import {isEmpty} from "@/utils";
import * as consts from "@/utils/constant.js";
import clUpload from '../../../uni_modules/cl-upload/components/cl-upload/cl-upload.vue'
// import uniRate from '@/uni_modules/uni-rate/'
export default {
  components:{
    clUpload
  },
  data() {
    return {
      show:false,
      content:'未查询到您的住宿信息，暂时无法申请维修！',
      rules:{
        repairsName: [{required: true,message: '请输入报修人',trigger: ['change','blur'],}],
        repairsProject: [{required: true,message: '请选择报修项目',trigger: ['change','blur'],}],
        building: [{required: true,message: '请输入宿舍楼栋',trigger: ['change','blur'],}],
        roomId: [{required: true,message: '请输入房间号',trigger: ['change','blur'],}],
        phoneNumber: [{
          required: true,
          message: '请输入手机号',
          trigger: ['change','blur'],
        },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.mobile(value);
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change','blur'],
          }],
      },
      form: {},
      sexList: [
        {
          name: '男',
          checked: false,
          disabled: false
        },
        {
          name: '女',
          checked: false,
          disabled: false
        }
      ],
      checkboxList: [
        {
          name: '是',
          checked: false,
          disabled: false
        },
        {
          name: '否',
          checked: false,
          disabled: false
        },
      ],
      radio: '',
      switchVal: false,
      showImages:false,
      showIdCardBadgeImages:false,
      showIdCardPortraitImgPreview:false,
      idCardPopup:true,
      idCardForm:{},
      isCRM:false,
      calendarShow:false,
      mode: 'date',
      //同行人员相关
      // 关系列表
      contactRelationList: [],
      showContactRelationSel:false,
      tzryPopup:false,
      tzryForm:{},
      isSuccess:false,
      videoList:[],
      fileList:[],
      clUplodUrl:consts.API_BASE_URL + '/xsdcrm-wechat-api/riders/maintain/signUpload',
      dormitoryId:'',
      uploadHeader:{
        Authorization:"Bearer " + uni.getStorageSync("token")
      }
    };
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  async onLoad(query) {
    let openId = uni.getStorageSync('openId')
    let res3 = await this.$api.dormitory.getLodgingInfo(openId)
    let data = res3.data
    if (isEmpty(data)) {
      this.show = true
      return
    }
    this.form.repairsName = data.name
    this.form.phoneNumber = data.phoneNumber
    this.form.building = data.buildingNo
    this.form.roomId = data.roomNo


    this.dormitoryId = query.dormitoryId
    this.contactRelationList = []
    let res = await this.$api.dormitory.getdictType('repairs_project');
    let data2 = res.data
    if (data2) {
      data2.forEach(item => {
        this.contactRelationList.push({ value: item.dictValue, label: item.dictLabel })
      })
    }

  },
  methods:{
    repairsProjectFunc(){
      this.showContactRelationSel = true
    },
    uploadRemove(index, lists, name) {
      delete this.fileList[index]
      this.fileList = this.fileList.filter(v => {
        return v
      })
    },
    uploadSuccess(reslut){
        let param = {
          maintainId:'',
          damageItem:reslut.fileName,
          status:1
        }
        this.fileList.push(param)
    },
    onSuccess(reslut){
      let param = {
        maintainId:'',
        damageItem:reslut.fileName,
        status:3
      }
      this.fileList.push(param)
      this.videoList.push((window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/') + reslut.fileName)
      console.log(reslut,this.fileList)
    },
    jointUrl(url) {
      // return (window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/')
      return (window.location.href.includes('/xsdcrm-wechat-ui/')?consts.API_BASE_URL+'/xsdcrm-static/upload/': '/profile/') + url
    },
    selectedContactRelation(e){
      this.form.repairsProject = e[0].value
      this.form.repairsProject2 = e[0].label
    },
    async submitFunc(type) {
      console.log(type)

      if (type == 'success') {
        uni.reLaunch({
          url: `/pages/HomePage/webIndex`
        })
        return
      }

      let flag = true
      let flag2 = true
      this.fileList.forEach(v=>{
        if (v.status == 1){
          flag = false
        }
        if (v.status == 3){
          flag2 = false
        }
      })
      if (flag) return uni.showToast({title:"请上传损坏照片",icon: "error",});
      if (flag2) return uni.showToast({title:"请上传损坏视频",icon: "error",});
      this.$refs.uForm.validate(async (valid) => {
        if (valid) {
          uni.showLoading({
            title: '申请中'
          });
            let openId = uni.getStorageSync('openId')
            this.form.openId = openId
            const {code,msg,data} = await this.$api.dormitory.addWeixiu(this.form).catch((e)=>{
            })
            let num = 0
            if (code == 200) {
              this.fileList.forEach((v,i)=>{
                v.maintainId = data
                v.openId = openId
                this.$api.dormitory.addPicture(v).catch((e)=>{})
                num++
              })
              console.log('num,this.fileList.length',num,this.fileList.length)
              if (num >= this.fileList.length) {
                uni.showToast({
                  title: '申请成功，请等待审核！',
                  icon: "none",
                });
                setTimeout(()=>{
                  uni.reLaunch({
                    url: `/pages/HomePage/webIndex`
                  })
                },500)
                this.isSuccess = true
                uni.hideLoading();
              }
            }
        } else {
          console.log('验证失败');
        }
      });
    },
    dateInterval(Time){
      // 获取今天的日期
      const today = new Date();
      const specifiedDateStr = Time;
      const specifiedDate = new Date(specifiedDateStr);
      const timeDiff = today.getTime() - specifiedDate.getTime();
      const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
      return daysDiff
    },
    nowTime(){
      const now = new Date();
      // 获取年、月、日
      const year = now.getFullYear();
      let month = (now.getMonth() + 1).toString().padStart(2, '0'); // 月份是从 0 开始计数的，使用padStart方法补零
      let day = now.getDate().toString().padStart(2, '0'); // 获取日期，使用padStart方法补零
      return year+'-'+month+'-'+day
    },
    changeCalendar(e) {
      const nowTime = this.nowTime()
      if (e.result != nowTime) {
        this.form.checkOutTime = e.result
      } else {
        this.form.checkOutTime =  '';
        uni.showToast({
          title: "离宿日期不可选择当天",
          icon: "none",
        });
      }
    },
    checkOutTimeFunc() {
      this.calendarShow = true
    },
    async confirmFunc() {
      console.log(this.$api)
      let { code, msg ,data } = await this.$api.dormitory.getRidInfoByIdCard(this.idCardForm.idCardNo).catch(()=>{});
      if (data){
          function judgeGender(idNumber) {
            // 获取身份证号的倒数第二位数字
            const genderDigit = parseInt(idNumber.charAt(idNumber.length - 2));
            // 判断性别
            if (genderDigit % 2 === 0) {
              return '女';
            } else {
              return '男';
            }
          }
         this.form.sex = judgeGender(data.idCardNo)
         this.isCRM = true
         let NewForm = Object.assign({},data,JSON.parse(JSON.stringify(this.form)));
         this.form = JSON.parse(JSON.stringify(NewForm))
         this.$forceUpdate();
      }
      this.idCardPopup = false
    },
    cancelFunc() {

    },
    radioGroupChange(){

    },
    // 删除身份证人像面
    onIdCardBadgeImgDelete() {
      this.form.idCardBadgeImages = null
      this.showIdCardBadgeImages = false
    },
    // 删除身份证国徽面
    onIdCardPortraitImgDelete() {
      this.form.idCardPortraitImages = null
      this.showIdCardPortraitImgPreview = false
    },
    //删除人脸照片
    onHandIdCardImgDelete(item,index) {
      delete this.fileList[index]
      this.fileList = this.fileList.filter(v =>{ return v })
      this.showImages = false
    },
    // 上传图片
    async uploadPic(file, name,type) {
      try {
        const res = await uploadImg(file,'/xsdcrm-wechat-api/wxseparateAgreement/signUpload',false);
        let param = {
          maintainId:'',
          damageItem:res.fileName,
          status:type
        }
        this.fileList.push(param)
      } catch (e) {
      }
    },
    // 照片选择后回调
    onHandIdCardChooseCallback(lists) {
      // 压缩图片
      compressImg({
        file: lists[0].file, success: (result) => {
          this.uploadPic(result,'repairsImage',1)
          this.showImages = true
        }
      })
    },
  }
};
</script>
<style scoped>
*{
  box-sizing: border-box;
}
  .view-class{
    width: 100%;
    height: 100vh;
  }
  .view-box{
    padding:0 30rpx;
    padding-bottom: 120rpx;
  }
  .container {
    height: 200vh;
    margin-top: 150rpx;
  }

  .sticky {
    width: 750rpx;
    height: 120rpx;
    background-color: #2979ff;
    color: #fff;
    padding: 24rpx;
  }
  .u-form-item{
    padding-right: 30rpx;
  }

  /deep/.u-star-wrap{
    line-height: 1;
  }
  .newAddImg{
    width:166rpx;
    height: 166rpx;
    overflow: hidden;
    margin: 5px;
    background: #f4f5f6;
    position: relative;
    border-radius: 5px;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    -webkit-box-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    flex-direction: column;
    align-items: center;
  }
</style>
